<!-- 公共按鈕 -->
<template>
  <view class="t-button" :style="{ ...getBackground, ...styles, position }">
    <slot name="header"></slot>
    <slot></slot>
    <slot name="footer"></slot>
  </view>
  <view
    v-if="position === 'fixed' && placeholder"
    :style="`height: ${placeholderHeight}px;backgroundColor: inherit;`"
  ></view>
</template>

<script lang="ts" setup>
  import { propTypes } from '@/utils/propTypes';
  import {
    ref,
    getCurrentInstance,
    onMounted,
    type PropType,
    type CSSProperties,
    nextTick,
    computed,
  } from 'vue';

  const props = defineProps({
    modelValue: propTypes.number,
    styles: {
      type: Object as PropType<CSSProperties>,
      default: {},
    },
    /** 是否为固定定位 */
    position: {
      type: String as PropType<CSSProperties['position']>,
      default: 'fixed',
    },
    /** 是否需要底部占位, 仅在固定定位时生效 */
    placeholder: propTypes.bool.def(true),
    /** 是否显示底色 */
    showBackground: propTypes.bool.def(false),
  });

  const emit = defineEmits(['update:modelValue']);
  // 获取盒子总高度
  const placeholderHeight = ref(0);

  const getBackground = computed(() => {
    return props.showBackground
      ? {
          backgroundColor: '#fff',
          boxShadow: '0px 4rpx 24rpx 0px rgba(150, 151, 153, 0.16)',
        }
      : {};
  });

  async function getHeight() {
    const ins: any = getCurrentInstance();
    const query = uni.createSelectorQuery().in(ins.proxy);
    await nextTick();
    await nextTick();
    query
      .select('.t-button')
      .boundingClientRect((res) => {
        const { height } = res as UniApp.NodeInfo;
        placeholderHeight.value = height ?? 0;
        emit('update:modelValue', height);
      })
      .exec();
  }
  onMounted(() => {
    if (props.position === 'fixed' && props.placeholder) getHeight();
  });
</script>

<style scoped>
  .t-button {
    box-sizing: border-box;
    background-color: inherit;
    width: 100%;
    left: 0;
    bottom: 0;
    z-index: 98;
    padding-top: 30rpx;
    padding-bottom: 30rpx;
    padding-left: 30rpx;
    padding-right: 30rpx;

    display: flex;
    flex-wrap: wrap;
  }
</style>
